﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace WholeSlideImageLibrary.Formats.GenericTiff
{
    public class GenericTiffImageIdentifier : IImageIdentifier
    {
        public string Name => "GenericTiff";

        public int HeaderSize => 16;

        public async ValueTask<ImageSourceType> IdentifyAsync(FileSourceInfo fileInfo, FileSourceReader reader, ReadOnlyMemory<byte> header, CancellationToken cancellationToken = default)
        {
            var image = new GenericTiffWholeSlideImage(fileInfo);
            try
            {
                await image.InitializeAsync(true, cancellationToken).ConfigureAwait(false);
                return ImageSourceType.SingleImage;
            }
            finally
            {
                await image.DisposeAsync().ConfigureAwait(false);
            }
        }

        public ValueTask<ImageSourceType> IdentifyAsync(DirectorySourceInfo directoryInfo, CancellationToken cancellationToken = default)
        {
            return new ValueTask<ImageSourceType>(ImageSourceType.None);
        }

        public ValueTask<WholeSlideImageCollection?> OpenImageCollectionAsync(FileSourceInfo fileInfo, FileSourceReader reader, CancellationToken cancellationToken = default)
        {
            return default;
        }

        public ValueTask<WholeSlideImageCollection?> OpenImageCollectionAsync(DirectorySourceInfo directoryInfo, CancellationToken cancellationToken = default)
        {
            return default;
        }

        public async ValueTask<WholeSlideImage?> OpenSingleImageAsync(FileSourceInfo fileInfo, FileSourceReader reader, CancellationToken cancellationToken = default)
        {
            GenericTiffWholeSlideImage? image = new GenericTiffWholeSlideImage(fileInfo);
            try
            {
                await image.InitializeAsync(false, cancellationToken).ConfigureAwait(false);
                return Interlocked.Exchange<GenericTiffWholeSlideImage?>(ref image, null);
            }
            finally
            {
                if (!(image is null))
                {
                    await image.DisposeAsync().ConfigureAwait(false);
                }
            }
        }

        public ValueTask<WholeSlideImage?> OpenSingleImageAsync(DirectorySourceInfo directoryInfo, CancellationToken cancellationToken = default)
        {
            return default;
        }
    }
}
